package com.poizon.infrastructure.idem.starter.mongodb;

import cn.hutool.core.util.StrUtil;
import com.poizon.infrastructure.idem.core.repo.IIdemDbStoreRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

@Slf4j
@ConditionalOnClass(value = MongoTemplate.class)
public class MongodbDbStoreInit {
    /**
     * 自定义mongodb的创建过程
     */
    @Bean(name = "idemMongoTemplate")
    public MongoTemplate idemMongoTemplate(Environment environment) {
        log.info(">初始化mongodbtemplate");
        String hosts = environment.getProperty("idem.mongo.host", "127.0.0.1");
        String port = environment.getProperty("idem.mongo.port", "27017");
        String username = environment.getProperty("idem.mongo.username", "mongo");
        String password = environment.getProperty("idem.mongo.password", "mongo");
        String database = environment.getProperty("idem.mongo.database", "idem");
        String connectionUrl = StrUtil.format("mongodb://{}:{}@{}:{}/{}", username, password, hosts, port, database);
        SimpleMongoClientDatabaseFactory factory = new SimpleMongoClientDatabaseFactory(connectionUrl);
        MongoTemplate mongoTemplate = new MongoTemplate(factory);
        return mongoTemplate;
    }

    @Bean(value = "mongodbIIdemDbStoreRepo")
    public IIdemDbStoreRepo mongodbIIdemDbStoreRepo(@Qualifier(value = "idemMongoTemplate") MongoTemplate mongoTemplate) {
        log.info(">成功初始化幂等存储实现mongodb");
        return new MongodbIIdemDbStoreRepo(mongoTemplate);
    }
}